package com.tanhua.dubbo.server.service;


import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId){
        try {


            //通过userid查询他的所有的好友
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> usersList = mongoTemplate.find(query, Users.class);

            if (CollUtil.isEmpty(usersList)) {
                //没有好友数据 不用继续往下进行操作
                return CompletableFuture.completedFuture("ok");
            }

            //将动态存入每个好友的时间线中
            for (Users users : usersList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setDate(System.currentTimeMillis());
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);
                mongoTemplate.save(timeLine, "quanzi_time_line_" + users.getFriendId());
            }

        }catch (Exception e){

            log.error("写入好友时间线失败 userId = "+userId +" , publishId = " +publishId,e);

            return CompletableFuture.completedFuture("error");
        }

        return CompletableFuture.completedFuture("ok");


    }

}
